package com.junrry.communication

import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.ComponentActivity
import com.junray.mqttmanager.ArrivedMsgFlow
import com.junray.mqttmanager.MQTTCallback
import com.junray.mqttmanager.MQTTConfig
import com.junray.mqttmanager.MQTTService
import com.junrry.communication.databinding.ActivityPcBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

class MQTTActivity : ComponentActivity() {

    private val TAG = "MQTTActivity_LJM"

    private lateinit var binding: ActivityPcBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPcBinding.inflate(layoutInflater)
        setContentView(binding.root)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        init()

        initListener()
    }

    private var conn: MQTTService.Connection? = null
    private fun init() {
        val config = MQTTConfig()
        config.serverUri = "tcp://221.215.132.218:28183"
        config.clientId = "my_client_id"
        config.subscriptionTopic = "my_topic1111"
        config.subscriptionTopics = arrayOf("my_topic1114", "my_topic1112", "my_topic1113")
        config.sendTopic = "my_topic111"
        conn = MQTTService.bind(this, config)
    }

    private fun initListener() {
        binding.btnSend.setOnClickListener {
            if (binding.etSend.text.toString().trim().isNullOrEmpty()) {
                Toast.makeText(this, "输入内容", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            conn?.sendMsg(binding.etSend.text.toString())
        }

        binding.btnReconnect.setOnClickListener {

        }

        conn?.setCallback(object : MQTTCallback {
            override fun onMQTTStatus(state: Int) {
                Log.d(TAG, "state = $state")
            }
        })

        scope.launch {
            ArrivedMsgFlow.msg.collect {
                if (it != null) {
                    Log.d(TAG, "state = ${it.topic}  ${it.message}")
                }
            }
        }
    }
    private val scope = CoroutineScope(Job() + Dispatchers.IO)
    override fun onDestroy() {
        scope.cancel()
        conn?.let { unbindService(it) }
        super.onDestroy()
    }

}